package jmind.core.aspect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

public final class JoinPoints {

    public static HttpServletRequest findRequest(final JoinPoint pjp) {
        for (final Object arg : pjp.getArgs()) {
            if (arg instanceof HttpServletRequest)
                return (HttpServletRequest) arg;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T> T findObject(final ProceedingJoinPoint pjp, Class<T> obj) {
        for (final Object arg : pjp.getArgs()) {
            if (obj.isInstance(arg))
                return (T) arg;
        }

        return null;
    }

    public static <T extends Annotation> T getAnnotation(final ProceedingJoinPoint pjp, Class<T> cla) {
        return getMethod(pjp).getAnnotation(cla);
    }

    public static Method getMethod(final ProceedingJoinPoint pjp) {
        final MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        final Method targetMethod = methodSignature.getMethod();
        return targetMethod;
    }

}
